import { Component, OnInit, ViewChild } from '@angular/core'
import { Router, ActivatedRoute } from '@angular/router' //路由引入
import { JsonApiService } from 'app/core/api/json-api.service'
import { config } from '../../shared/smartadmin.config'

declare var $: any
@Component({
  selector: 'sa-device-event',
  templateUrl: './device-event.component.html',
  styleUrls: ['./device-event.component.css']
})
export class DeviceEventComponent implements OnInit {
  tableData: any = [] // table的表单数据
  totalCounts: number = 0 //分页总条数
  curPage: number = 1 //分页当前页
  pageSize: number = 10 //内置的分页每页条数
  activeSelected: string = '' //row高亮
  // 查询参数
  selectedDeviceId: any = '' // 选中的设备ID
  selectedCarNumber: any = '' // 选中的车牌号
  startDate: any = '' // 开始时间
  endDate: any = '' // 结束时间
  userName: any = '' // 操作人
  searchKey: any = '' // 用户的搜索关键字

  constructor(private router: Router, private activatedRoute: ActivatedRoute, private jsonApiService: JsonApiService) {
    activatedRoute.queryParams.subscribe(queryParams => {})
  }
  ngOnInit() {
    // this.load();
    this.initCarTree()
    this.initSelect2()

    this.initBtn()
  }

  //初始化车辆
  initCarTree() {
    System.import('script-loader!select2/dist/js/select2.min.js').then(() => {
      System.import('assets/js/select2-zh-CN.js').then(() => {
        var that = this
        $('#carNumberSelect2')
          .select2({
            language: 'zh-CN',
            placeholder: '请选择',
            minimumInputLength: 2, //最少2个字符，select2才显示查询的内容
            ajax: {
              url: config.BaseURL + 'stats/carListByCarNumber.html',
              dataType: 'json',
              delay: 50,
              method: 'POST',
              xhrFields: { withCredentials: true },
              data: function (params) {
                return {
                  carNumber: params.term // search term
                }
              },
              processResults: function (data, params) {
                var options = new Array()
                // 小于10个数量才判断重复
                if (data.data.length <= 10) {
                  let arr = []
                  let sameCar = []
                  // 判断相同的车牌号
                  for (let index = 0; index < data.data.length; index++) {
                    let car = data.data[index]
                    if (arr.indexOf(car.carNumber) != -1) {
                      sameCar.push(car.carNumber)
                    } else {
                      arr.push(car.carNumber)
                    }
                  }
                  $(data.data).each(function (index, car) {
                    if (sameCar.indexOf(car.carNumber) != -1) {
                      options.push({
                        id: car.deviceId,
                        text: car.carNumber + '[' + car.parentName + ']'
                      })
                    } else {
                      options.push({
                        id: car.deviceId,
                        text: car.carNumber
                      })
                    }
                  })
                } else {
                  $(data.data).each(function (index, car) {
                    options.push({
                      id: car.deviceId,
                      text: car.carNumber
                    })
                  })
                }
                return {
                  results: options //获取查询后的结果
                }
              },
              cache: true
            },
            templateResult: this.formatRepo
          })
          .on('select2:select', function (e) {
            var data = e.params.data
            that.selectedDeviceId = data.id
            if (data.text.indexOf('[') > 0) {
              that.selectedCarNumber = data.text.split('[')[0]
            } else {
              that.selectedCarNumber = data.text
            }
          })
      })
    })
  }
  //select2 格式回调函数
  formatRepo(state) {
    if (!state.id) {
      return state.text
    }
    var $state = $('<span><i class="fa fa-car green"></i>&nbsp;&nbsp;' + state.text + '</span>')
    return $state
  }
  //清除车辆选中值
  del_carNumber() {
    this.selectedDeviceId = ''
    this.selectedCarNumber = ''
    var str = $("<span class='select2-selection__placeholder'>请选择</span>")
    $('#carNumberSelect2').val('')
    $('#select2-carNumberSelect2-container').empty()
    $('#select2-carNumberSelect2-container').attr('title', '')
    $('#select2-carNumberSelect2-container').prepend(str)
  }
  // 时间选择回调
  dateSelect(time) {
    this.startDate = time.startTime
    this.endDate = time.endTime
    this.load()
  }
  initSelect2() {
    System.import('script-loader!select2/dist/js/select2.min.js').then(() => {
      System.import('assets/js/select2-zh-CN.js').then(() => {
        $('#tcarTypeSelect2').select2({ language: 'zh-CN' })
      })
    })
  }

  // 事件分类
  event: any = [
    {
      id: '01',
      label: '车辆信息',
      children: [
        {
          id: '0101',
          label: '车辆安装'
        },
        {
          id: '0106',
          label: '车辆删除'
        },
        {
          id: '0102',
          label: '变更车牌'
        },
        {
          id: '0103',
          label: '变更厂区'
        },
        {
          id: '0104',
          label: '车辆共享'
        },
        {
          id: '0105',
          label: '重置设备ID'
        }
      ]
    },
    {
      id: '02',
      label: '设备信息',
      children: [
        {
          id: '0201',
          label: '固件升级'
        },
        {
          id: '0202',
          label: '更新系数'
        },
        {
          id: '0203',
          label: '远程清零'
        },
        {
          id: '0204',
          label: '设置频率'
        },
        {
          id: '0205',
          label: '远程重启'
        },
        {
          id: '0206',
          label: '恢复设置'
        },
        {
          id: '0207',
          label: '轨迹修复'
        },
        {
          id: '0208',
          label: '数据修复'
        }
      ]
    },
    {
      id: '03',
      label: '维修信息',
      children: [
        {
          id: '0301',
          label: '更换主机'
        },
        {
          id: '0302',
          label: '更换传感器'
        },
        {
          id: '0303',
          label: '更换线材'
        },
        {
          id: '0304',
          label: '更换采集器'
        },
        {
          id: '0305',
          label: '更换GPS'
        }
      ]
    },
    {
      id: '04',
      label: '限制信息',
      children: [
        {
          id: '0401',
          label: '限制进厂'
        }
      ]
    }
  ]
  eventObj: any = {
    '0101': '车辆安装',
    '0102': '变更车牌',
    '0103': '变更厂区',
    '0104': '车辆共享',
    '0105': '重置设备ID',
    '0106': '车辆删除',
    '0201': '固件升级',
    '0202': '更新系数',
    '0203': '远程清零',
    '0204': '设置频率',
    '0205': '远程重启',
    '0206': '恢复设置',
    '0207': '轨迹修复',
    '0208': '数据修复',
    '0301': '更换主机',
    '0302': '更换传感器',
    '0303': '更换线材',
    '0304': '更换采集器',
    '0305': '更换GPS',
    '0401': '限制进厂'
  }
  // 获取列表数据
  load() {
    let param = {
      pageSize: this.pageSize,
      nowPage: this.curPage,
      parameters: {
        deviceId: this.selectedDeviceId,
        startDateStr: this.startDate,
        endDateStr: this.endDate,
        userName: this.userName,
        type: $('#tcarTypeSelect2').val(),
        searchKey: common.stringTrim(this.searchKey)
      }
    }
    let reqdata = 'gridPager=' + JSON.stringify(param)
    this.jsonApiService.http('logForDeviceEvent/list.html', reqdata).subscribe(result => {
      let data = []
      if (result.isSuccess && result.exhibitDatas) {
        data = result.exhibitDatas
        // 将类型进行映射
        for (let i = 0; i < result.exhibitDatas.length; i++) {
          result.exhibitDatas[i].typeStr = this.eventObj[result.exhibitDatas[i].type]
        }
        this.tableData = result.exhibitDatas
        this.totalCounts = result.recordCount
      }
    })
  }

  // 分页回调
  paginate(e) {
    this.activeSelected = ''
    this.curPage = e.page + 1
    this.pageSize = e.rows
    this.load()
  }
  // 刷新表
  refresh() {
    this.load()
  }
  // 表单查询
  tableSearch() {
    this.curPage = 1
    this.load()
  }

  // 数据导出
  exportData() {
    const param = {
      deviceId: this.selectedDeviceId,
      startDateStr: this.startDate,
      endDateStr: this.endDate,
      userName: this.userName,
      type: $('#tcarTypeSelect2').val(),
      searchKey: common.stringTrim(this.searchKey)
    }
    let timeCheck = common.correctTime(param, [], ['startDateStr', 'endDateStr'])
    if (!timeCheck.status) {
      this.jsonApiService.message(timeCheck.message)
      return
    }
    common.exprotDataFile(param, 'param', config.BaseURL + 'logForDeviceEvent/exportDeviceEvent.html')
  }

  // 关联维修
  relationTableData: any = []
  curRowId: ''
  relationRepair(row: any, modal: any) {
    let param = {
      deviceId: row.deviceId,
      deviceRepairedId: row.deviceRepairedId
    }
    this.curRowId = row.id
    this.selected = []
    this.rowDetailed = []
    this.jsonApiService
      .json_http('deviceRepairedV2/findDeviceRepairedListByTimeAndCarNumber.html', param)
      .subscribe(result => {
        this.relationTableData = result.data
        this.relationTableData.map(item => {
          item.isChecked = false
          if (row.deviceRepairedId === item.id) {
            item.isChecked = true
            this.selected = [item]
            this.getRepairDetailed(item)
          }
        })
        modal.show()
      })
  }
  cancelRelationModalModal(modal) {
    this.relationTableData = []
    modal.hide()
  }

  allChecked: boolean = false // table全选状态值
  selected: any[] = [] // row选择的数据
  rowDetailed: any[] = [] // 维修明细列表
  /**
   * 单行数据选中事件,仅支持单行选中,不支持多选
   */
  //table复选框数据row选中事件回调:处理选中状态和deviceId
  rowSelected(row, e, index) {
    var index = $.inArray(row, this.selected)
    this.relationTableData.map(item => {
      item.isChecked = false
    })
    if (index === -1) {
      row.isChecked = true
      this.selected = [row]
      this.getRepairDetailed(row)
    } else {
      row.isChecked = false
      this.selected = []
      this.rowDetailed = []
    }
  }

  // 大类的数组 现象的数组
  pTypeList: any = ['离线问题', 'GPS问题', '传感器问题', '甩挂问题']
  // 小类的数组 内容的数组
  typeList: any = [
    '更换主机',
    '电源维修',
    '更换线材',
    '挪动天线位置',
    '更换天线',
    'V4换V7',
    '更换传感器',
    '重新焊接',
    '离线其他',
    'GPS其他',
    '传感器其他',
    '无维修'
  ]
  getRepairDetailed(row: any) {
    if (row.isChecked) {
      let param = 'deviceRepairedId=' + row.id
      this.jsonApiService.http2('deviceRepairedV2/getDeviceRepairedDetailListById.html', param).subscribe(result => {
        this.rowDetailed = result.data
      })
    }
  }

  cancelRelationSubmit(modal) {
    if (this.selected.length) {
      const selectRow = this.selected[0]
      let param = 'deviceEventId=' + this.curRowId + '&deviceRepairedId=' + selectRow.id
      this.jsonApiService.http2('logForDeviceEvent/updateDeviceRepairedId.html', param).subscribe(result => {
        if (result.success) {
          modal.hide()
          this.jsonApiService.message('操作成功')
          this.load()
        } else {
          this.jsonApiService.message(result.message)
        }
      })
    } else {
      this.jsonApiService.message('请选择关联维修记录')
    }
  }

  // 不关联
  notAssociated(modal) {
    let param = 'deviceEventId=' + this.curRowId + '&deviceRepairedId='
    this.jsonApiService.http2('logForDeviceEvent/updateDeviceRepairedId.html', param).subscribe(result => {
      if (result.success) {
        modal.hide()
        this.jsonApiService.message('操作成功')
        this.load()
      } else {
        this.jsonApiService.message(result.message)
      }
    })
  }

  /**
   * 编辑
   */
  repairContentStr: any = ''
  repairContent: any = []
  repairContentId: any = ''
  repairedPType: string = '' // 故障现象
  repairedType: string = '' // 维修内容
  faultPhenomenon: string = '' // 故障现象详细
  faultPhenomenonList: any = [] //故障现象详细数据
  repairedPTypeChange() {
    this.faultPhenomenon = ''
    this.faultPhenomenonList = []
    switch (this.repairedPType) {
      case '1':
        this.faultPhenomenonList = [
          {
            label: '请选择',
            value: ''
          },
          {
            label: '离线',
            value: '离线'
          },
          {
            label: '在线',
            value: '在线'
          }
        ]
        break
      case '2':
        this.faultPhenomenonList = [
          {
            label: '请选择',
            value: ''
          },
          {
            label: '正常',
            value: '正常'
          },
          {
            label: '偶尔丢失',
            value: '偶尔丢失'
          },
          {
            label: '大段丢失',
            value: '大段丢失'
          },
          {
            label: '停车速度平直',
            value: '停车速度平直'
          },
          {
            label: '无GPS',
            value: '无GPS'
          }
        ]
        break
      case '3':
        this.faultPhenomenonList = [
          {
            label: '请选择',
            value: ''
          },
          {
            label: '正常',
            value: '正常'
          },
          {
            label: '正负52万',
            value: '正负52万'
          },
          {
            label: '经常52万',
            value: '经常52万'
          },
          {
            label: '偶尔52万',
            value: '偶尔52万'
          },
          {
            label: '乱跳',
            value: '乱跳'
          },
          {
            label: '形变小',
            value: '形变小'
          },
          {
            label: '平直',
            value: '平直'
          },
          {
            label: '方向反',
            value: '方向反'
          },
          {
            label: '全部平直',
            value: '全部平直'
          }
        ]
        break
      case '4':
        this.faultPhenomenonList = [
          {
            label: '请选择',
            value: ''
          },
          {
            label: '无故障',
            value: '无故障'
          }
          
        ]
        break
    }
  }
  editRow(row, modal) {
    this.repairContentId = row.id
    this.repairContent = JSON.parse(JSON.stringify(row.repairContent))
    this.repairedPType = row.pType + ''
    this.repairedType = row.type + ''
    this.repairedPTypeChange()
    this.faultPhenomenon = row.faultPhenomenon == '离线问题' ? '离线' : row.faultPhenomenon
    modal.show()
  }
  editClose(modal) {
    modal.hide()
  }
  addNum(index) {
    if (this.repairContent[index]) {
      var content = ''
      this.repairContent.push(content)
    }
  }
  // 数量减
  reduceNum(index) {
    this.repairContent.splice(index, 1)
  }
  contentChange(value, index) {
    this.repairContent[index] = value
  }
  editSubmit(modal) {
    if (this.repairContent.length < 1) {
      this.jsonApiService.message('必须要有一条维修细分')
      return
    }
    if (!this.repairedPType) {
      this.jsonApiService.message('请选择故障现象')
      return
    }
    if (!this.faultPhenomenon) {
      this.jsonApiService.message('请选择故障现象详情')
      return
    }
    if (!this.repairedType) {
      this.jsonApiService.message('请选择维修内容')
      return
    }
    let reqdata = {
      id: this.repairContentId,
      repairContentStr: JSON.stringify(this.repairContent),
      pType: this.repairedPType,
      type: this.repairedType,
      faultPhenomenon: this.faultPhenomenon
    }
    this.jsonApiService.http_obj('deviceRepairedV2/editDeviceRepairedDetailV2.html', reqdata).subscribe(data => {
      if (data.success) {
        modal.hide()
        this.getRepairDetailed(this.selected[0])
      } else {
        this.jsonApiService.message(data.message)
      }
    })
  }

  btnData: any = []
  editCheck: boolean = false
  // 维修明细编辑权限按钮
  initBtn() {
    this.btnData = JSON.parse(decodeURIComponent(localStorage.getItem('cargpsw_device:repaire:detail')))
    if (!this.btnData) {
      return
    }
    for (let item of this.btnData) {
      if (item.sourceKey === 'repaireDetail:editCheck' && item.parentId) {
        this.editCheck = true
      }
    }
  }
}
